import { pageWhiteList } from '@/model/index';

// 登录页面路径
const loginRoute = '/pages/index/login';
export const isLogined = () => {
	return uni.getStorageSync('token') !== ''; // 检查是否有 token
};

export const judgeLoginStatus = (url: string) => {
	if (isLogined()) {
		return true;
	}
	
	const path = url.split('?')[0];
	if (pageWhiteList.includes(path)) {
		return true;
	}
	
	const redirectRoute = loginRoute;
	uni.navigateTo({ url: redirectRoute });
	return false;
}

const navigateToInterceptor = {
	invoke({ url }: { url: string }) {
		return judgeLoginStatus(url);
	},
	fail(err: any) {
		console.error(`拦截器报错: `, err);
	}
};

const methods = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab'];
export const pageInterceptor = {
	install() {
		methods.forEach((item: string) => uni.addInterceptor(item, navigateToInterceptor));
	}
};